import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../../../components/appbar.dart';
import '../../../utils/methods.dart';
import '../../../config/colors.dart';
import '../../../provider/model.dart';
import './exam_comps.dart';

class SequenceExam extends StatefulWidget {
  @override
  _SequenceExamState createState() => _SequenceExamState();
}

class _SequenceExamState extends State<SequenceExam> with SingleTickerProviderStateMixin {
  int model = 1;     // 题目类型 1:答题  2:背题  
  int layer = 3;     // 显示浮层 0:不显示  1:设置浮层  2:题目浮层  3:遮挡跳转
  bool err = false;   // 是否做错题
  PageController _examsPageCtrl = PageController(initialPage: 0);
  int curPage = 0;
  bool showSettingLayer = false;
  bool nextItem = false;
  double fontSizeVal = 25;
  int subjectItemsHeight = -724;
  List<Map> itemsErr;
  List<Map> itemsErrCopy;

  // 动画控制
  AnimationController subjectItemsHeiCtrl;
  Animation<double> subjectItemsHeiAnimation;

  // 题目
  List subjectList = [];

  @override
  void initState() {
    _initData();
    _initController();
    _initAnimation();
    getSubjectList();
    super.initState();
  }

  @override
  void deactivate() {
    super.deactivate();
  }

  @override
  void dispose() {
    subjectItemsHeiCtrl?.dispose();
    super.dispose();
  }

  // 获取storage中的科目数据
  void getSubjectList() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String subject1 = prefs.getString('subject1');
    List list = json.decode(subject1);
    setState(() {
      subjectList = list;
      itemsErr = new List(list.length);
      itemsErrCopy = new List(list.length);
    });
    int index = Provider.of<SubLenModel>(context, listen: false).curSubIndex - 1;
    _examsPageCtrl.animateToPage(index, curve: Curves.linear, duration: Duration(milliseconds: 2));
    const time = const Duration(milliseconds: 500);
    Timer(time, () {
      setState(() {
        layer = 0;
      });
    });
  }

  void _initController() {
    subjectItemsHeiCtrl = AnimationController(
      duration: Duration(milliseconds: 200),
      vsync: this
    );
  }

  void _initAnimation() {
    subjectItemsHeiAnimation = Tween<double>(
      begin: -724.0,
      end: 0
    ).animate(
      CurvedAnimation(
        parent: subjectItemsHeiCtrl,
        curve: Interval(0.0, 1.0, curve: Curves.ease)
      )
    )..addListener(() {
      setState(() {
        subjectItemsHeight = subjectItemsHeiAnimation.value.floor();
      });
    });
  }

  void _initData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool next = prefs.getBool('nextItem');
    setState(() {
      nextItem = next == null ? false : next;
    });
    print(nextItem);
  }

  // 顶部导航栏按钮
  Widget appBarBtns() {
    return Row(
      children: <Widget>[
        GestureDetector(
          onTap: () {
            if(model == 1) return;
            List<Map> itemsErr = this.itemsErr;
            List<Map> itemsErrCopy = this.itemsErrCopy;
            for(int i=0, len=itemsErr.length; i<len; i++) {
              if(itemsErrCopy[i] == null) {
                itemsErr[i] = null;
              }
            }
            setState(() {
              model = 1;
              itemsErr = itemsErr;
            });
          },
          child: Container(
            width: fitSize(110),
            height: fitSize(52),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: model == 1 ? Theme.of(context).primaryColorDark : Theme.of(context).primaryColor,
              border: Border.all(
                color: Theme.of(context).primaryColorDark
              ),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(4.0),
                bottomLeft: Radius.circular(4.0)
              )
            ),
            child: Text(
              '答题', 
              style: TextStyle(
                color: model == 1 ? Theme.of(context).primaryColor : Theme.of(context).primaryColorDark, 
                fontSize: 12.0
              )
            ),
          ),
        ),
        GestureDetector(
          onTap: () {
            if(model == 2) return;
            List<Map> itemsErr = this.itemsErr;
            List<Map> itemsErrCopy = this.itemsErrCopy;
            for(int i=0, len=itemsErr.length; i<len; i++) {
              if(itemsErr[i] == null) {
                Map item = {};
                item['isErr'] = false;
                item['index'] = 1;
                itemsErr[i] = item;
                itemsErrCopy[i] = null;
              }else{
                itemsErrCopy[i] = itemsErr[i];
              }
            }
            setState(() {
              model = 2;
              itemsErr = itemsErr;
              itemsErrCopy = itemsErrCopy;
            });
          },
          child: Container(
            width: fitSize(110),
            height: fitSize(52),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: model == 2 ? Theme.of(context).primaryColorDark : Theme.of(context).primaryColor,
              border: Border.all(
                color: Theme.of(context).primaryColorDark
              ),
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(4.0),
                bottomRight: Radius.circular(4.0)
              )
            ),
            child: Text(
              '背题', 
              style: TextStyle(
                color: model == 2 ? Theme.of(context).primaryColor: Theme.of(context).primaryColorDark, 
                fontSize: 12.0
              )
            ),
          ),
        ),
      ],
    );
  }

  // 题目内容
  Widget questionContent(Map content, int index) {
    bool isErr = model == 2 || (this.itemsErr[index] != null && this.itemsErr[index]['isErr'] == true);

    return SingleChildScrollView(
      child: Container(
        width: MediaQuery.of(context).size.width,
        padding: EdgeInsets.only(
          left: fitSize(30),
          right: fitSize(30),
          top: fitSize(25),
          bottom: fitSize(35)
        ),
        decoration: BoxDecoration(
          color: Theme.of(context).primaryColor
        ),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            questionType(content),
            questionResult(content, index),
            isErr ? questionErrorTip(content, index) : SizedBox(),
            isErr ? QuestionSkill(content: content) : SizedBox(),
            SizedBox(height: fitSize(90))
          ]
        )
      )
    );
  }

  // 题目类型
  Widget questionType(Map content) {
    return Stack(
      alignment: Alignment.topLeft,
      children: <Widget>[
        Text(
          '          ${content["content"]}',
          style: TextStyle(
            height: 1.4,
            fontSize: fitSize(34),
            color: Theme.of(context).primaryColorDark
          ),
        ),
        Container(
          width: fitSize(65),
          height: fitSize(35),
          margin: EdgeInsets.only(
            top: 4.0
          ),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Color(AppColors.assistBlue),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(4.0),
              topRight: Radius.circular(4.0),
              bottomRight: Radius.circular(4.0),
            )
          ),
          child: Text(content['type'] == 0 ? '判断' : '单选', style: TextStyle(fontSize: 11.0, color: Theme.of(context).primaryColor,)),
        )
      ],
    );
  }

  // 题目答案
  Widget questionResult(Map content, int index) {
    List<String> resultKeys = ['select_a', 'select_b', 'select_c', 'select_d', 'select_e', 'select_f', 'select_g', 'select_h'];
    List<String> showKeys = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
    List<Widget> resItems = [];

    for(int i=0; i<resultKeys.length; i++) {
      List<dynamic> item = [];
      if(content[resultKeys[i]] != '') {
        item.add(showKeys[i]);      // 选项
        item.add(content[resultKeys[i]]);   // 选项内容
        item.add(index);         // 题目序号
        item.add(i);             // 答案序号
        resItems..add(questionResItem(item, content));
      }
    }

    return Container(
      margin: EdgeInsets.only(
        top: fitSize(46)
      ),
      child: Column(
        children: resItems,
      ),
    );
  }

  // 题目选项
  Widget questionResItem(List answer, Map content) {
    double resWidth = MediaQuery.of(context).size.width - fitSize(84+60);
    bool isErr = this.itemsErr[answer[2]] != null && this.itemsErr[answer[2]]['isErr'] == true && this.itemsErr[answer[2]]['index'] == answer[3];
    bool right = content['answer'] == answer[0] && this.itemsErr[answer[2]] != null && this.itemsErr[answer[2]]['isErr'] != null;
    ThemeData theme = Theme.of(context);
    return Container(
      margin: EdgeInsets.only(bottom: fitSize(46)),
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              bool disable = this.model == 2 || (this.itemsErr[answer[2]] != null && this.itemsErr[answer[2]]['isErr'] != null);
              if(disable) return;
              int index = answer[2];
              Map err = {};
              List<Map> itemsRes = this.itemsErr;
              if(answer[0] == content['answer']) {
                err['isErr'] = false;
              }else{
                err['isErr'] = true;
              }
              err['index'] = answer[3]; 
              itemsRes[index] = err;
              setState(() {
                itemsErr = itemsRes;
              });
              if(content['answer'] == answer[0]) {
                Provider.of<SubLenModel>(context, listen: false).increaseRightNum();
                _examsPageCtrl.animateToPage(this.curPage + 1, curve: Curves.ease, duration: Duration(milliseconds: 800));
              }else{
                Provider.of<SubLenModel>(context, listen: false).increaseErrNum();
              }
            },
            child: Container(
              width: fitSize(60),
              height: fitSize(60),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(27),
                color: isErr ? theme.errorColor : (right ? theme.accentColor : theme.primaryColor),
                boxShadow: [
                  BoxShadow(
                    color: Color(AppColors.grayColor99),
                    offset: Offset(0.0, 0.0),
                    blurRadius: 4.0,
                    spreadRadius: 0.5
                  )
                ]
              ),
              child: Text(
                answer[0], 
                style: TextStyle(
                  fontSize: fitSize(32),
                  color: isErr ? theme.primaryColor : (right ? theme.primaryColor : theme.primaryColorDark)
                )
              ),
            ),
          ),
          SizedBox(width: fitSize(24)),
          Container(
            width: resWidth,
            child: Wrap(
              children: <Widget>[
                Text(
                  answer[1], 
                  style: TextStyle(
                    fontSize: fitSize(34), 
                    color: isErr ? theme.errorColor : (right ? theme.accentColor : theme.primaryColorDark)
                  )
                )
              ],
            ), 
          )
        ],
      )
    );
  }

  // 选择错误时提示信息
  Widget questionErrorTip(Map content, int index) {
    // bool isErr = model == 2 || (this.itemsErr[index] != null && this.itemsErr[index]['isErr'] == true);

    return Container(
      height: fitSize(85),
      padding: EdgeInsets.only(left: fitSize(30), right: fitSize(30)),
      margin: EdgeInsets.only(top: fitSize(20)),
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text('答案', style: TextStyle(color: Theme.of(context).primaryColorDark),),
              SizedBox(width: fitSize(12)),
              Text(content['answer'], style: TextStyle(color: Theme.of(context).accentColor)),
              SizedBox(width: fitSize(12)),
              // isErr ? Text('你选择', style: TextStyle(color: Theme.of(context).primaryColorDark),) : SizedBox(),
              // SizedBox(width: fitSize(12)),
              // isErr ? Text('B', style: TextStyle(color: Theme.of(context).errorColor)) : SizedBox()
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Icon(Icons.wb_sunny, size: 14.0, color: Color(AppColors.assistBlue)),
              SizedBox(width: 4.0),
              Text('速记口诀', style: TextStyle(color: Color(AppColors.assistBlue)))
            ],
          )
        ],
      ),
    );
  }

  // 显示设置浮层
  Widget setting() {
    return Consumer<ExamTopicModel>(
      builder: (context, etm, child) {
        return GestureDetector(
          onTap: () {
            print('拉起设置');
            setState(() {
              layer = 1;
            });
          },
          child: Container(
            width: fitSize(100),
            height: 50.0,
            alignment: Alignment.centerRight,
            color: Theme.of(context).primaryColor,
            child: Text('设置', style: TextStyle(fontSize: 12.0, color: Theme.of(context).primaryColorDark))
          )
        );
      },
    );
  }

  // 设置选项
  Widget settingItems() {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: fitSize(500),
      padding: EdgeInsets.only(
        left: fitSize(30),
        right: fitSize(30)
      ),
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10.0),
          topRight: Radius.circular(10.0)
        )
      ),
      child: Column(
        children: <Widget>[
          settingAutoToNext(),
          SizedBox(height: fitSize(34)),
          // settingFontSize(),
          Container(
            child: Consumer<ExamTopicModel>(
              builder: (context, etm, child) {
                return RaisedButton(
                  child: Text('切换主题'),
                  onPressed: () {
                    etm.switchExamTopic();
                  },
                );
              },
            ),
          )
        ],
      ),
    );
  }

  // 设置选项--自动跳转下一题
  Widget settingAutoToNext() {
    return Container(
      width: double.infinity,
      height: fitSize(100),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '答对自动跳转下一题', 
            style: TextStyle(
              color: Theme.of(context).primaryColorLight,
              fontSize: fitSize(30),
              decoration: TextDecoration.none,
              fontWeight: FontWeight.w500
            )
          ),
          CupertinoSwitch(
            value: this.nextItem,
            activeColor: Theme.of(context).primaryColorDark,
            onChanged: (bool val) {
              setState(() {
                nextItem = val;
              });
              setStorage('nextItem', val);
            },
          )
        ],
      ),
    );
  }

  // 设置选项--设置字体大小
  Widget settingFontSize() {
    return Container(
      width: double.infinity,
      height: fitSize(140),
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Row(
                children: <Widget>[
                  SizedBox(width: fitSize(38)),
                  Text(
                    '小',
                    style: TextStyle(
                      decoration: TextDecoration.none,
                      fontSize: 14.0,
                      color: Theme.of(context).primaryColorLight,
                      fontWeight: FontWeight.w200
                    ),
                  ),
                ],
              ),
              Text(
                '普通',
                style: TextStyle(
                  decoration: TextDecoration.none,
                  fontSize: 22.0,
                  color: Theme.of(context).primaryColorLight,
                  fontWeight: FontWeight.w200
                )
              ),
              Row(
                children: <Widget>[
                  Text(
                    '大',
                    style: TextStyle(
                      decoration: TextDecoration.none,
                      fontSize: 14.0,
                      color: Theme.of(context).primaryColorLight,
                      fontWeight: FontWeight.w200
                    )
                  ),
                  SizedBox(width: fitSize(50))
                ],
              )
            ],
          ),
          SizedBox(
            height: fitSize(14)
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                'A',
                style: TextStyle(
                  fontSize: 18,
                  color: Theme.of(context).primaryColorDark,
                  decoration: TextDecoration.none,
                  fontWeight: FontWeight.w200
                ),
              ),
              Container(
                width: fitSize(560),
                child: Text('name')
              ),
              Text(
                'A',
                style: TextStyle(
                  fontSize: 24,
                  color: Theme.of(context).primaryColorDark,
                  decoration: TextDecoration.none,
                  fontWeight: FontWeight.w200
                )
              )
            ],
          )
        ],
      ),
    );
  }
  
  // 设置浮层
  Widget settingLayer() {
    return Stack(
      alignment: Alignment.bottomLeft,
      children: <Widget>[
        GestureDetector(
          onTap: () {
            print('hidelayer');
            setState(() {
              layer = 0;
            });
          },
          child: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            color: Color.fromRGBO(0, 0, 0, 0.5)
          ),
        ),
        settingItems()
      ],
    );
  }

  // 考试题目浮层
  Widget examsLayer() {
    Widget bgLayer;

    if(this.layer == 2) {
      bgLayer = Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color: Color.fromRGBO(0, 0, 0, 0.5)
      );
    }else{
      bgLayer = Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
      );
    }

    return Stack(
      alignment: Alignment.bottomLeft,
      children: <Widget>[
        GestureDetector(
          onTap: () {
            print('hide exam layer');
            subjectItemsHeiCtrl.reverse();
            setState(() {
              layer = 0;
            });
          },
          child: bgLayer
        ),
        Positioned(
          bottom: fitSize(this.subjectItemsHeight),
          child: Container(
            width: MediaQuery.of(context).size.width,
            height: fitSize(800),
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              border: Border(
                top: BorderSide(
                  color: Theme.of(context).bottomAppBarColor
                )
              )
            ),
            child: subjectItemsList(),
          )
        )
      ],
    );
  }

  // 考试题目内容
  Widget subjectItemsList() {
    return Column(
      children: <Widget>[
        subjectRecord(),
        subjectIndexList()
      ],
    );
  }

  // 考试统计
  Widget subjectRecord() {
    return Container(
      height: fitSize(76),
      padding: EdgeInsets.only(left: fitSize(30), right: fitSize(30)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: <Widget>[
              Icon(Icons.star_border, size: 18, color: Theme.of(context).primaryColorLight),
              SizedBox(width: fitSize(6)),
              Text(
                '收藏', 
                style: TextStyle(
                  fontSize: fitSize(26), 
                  color: Theme.of(context).primaryColorDark,
                  decoration: TextDecoration.none,
                  fontWeight: FontWeight.w400
                )
              )
            ],
          ),
          AnswerResult(),
          GestureDetector(
            onTap: () {
              subjectItemsHeiCtrl.forward();
              setState(() {
                layer = 2;
              });
            },
            child: Container(
              height: fitSize(76),
              color: Theme.of(context).primaryColor,
              child: Row(
                children: <Widget>[
                  Icon(
                    Icons.widgets,
                    size: 16,
                    color: Theme.of(context).primaryColorLight,
                  ),
                  SizedBox(width: fitSize(8)),
                  Text(
                    '${this.curPage + 1}',
                    style: TextStyle(
                      fontSize: fitSize(26), 
                      color: Theme.of(context).primaryColorDark,
                      decoration: TextDecoration.none,
                      fontWeight: FontWeight.w400
                    )
                  ),
                  Consumer<SubLenModel>(
                    builder: (context, slm, child) {
                      return Text(
                        '/${slm.sub1Len}',
                        style: TextStyle(
                          fontSize: fitSize(26), 
                          color: Theme.of(context).primaryColorLight,
                          decoration: TextDecoration.none,
                          fontWeight: FontWeight.w400
                        )
                      );
                    }
                  ),
                  
                ],
              ) 
            )
          )
        ],
      ),
    );
  }

  // 题目序号
  Widget subjectIndexList() {
    return Consumer<SubLenModel>(
      builder: (context, slm, child) {
        return Container(
          height: fitSize(720),
          child: GridView.builder(
            itemCount: slm.sub1Len,
            primary: true,
            addRepaintBoundaries: false,
            padding: EdgeInsets.only(
              top: fitSize(10),
              left: fitSize(30), 
              right: fitSize(30),
              bottom: fitSize(20)
            ),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 6,
              mainAxisSpacing: fitSize(20),
              crossAxisSpacing: fitSize(40)
            ),
            itemBuilder: (BuildContext context, int index) {
              return GestureDetector(
                onTap: () {
                  _examsPageCtrl.animateToPage(index, curve: Curves.linear, duration: Duration(milliseconds: 10));
                  subjectItemsHeiCtrl.reverse();
                  setState(() {
                    layer = 0;
                  });
                },
                child: SubjectIndex(index: index) 
              );
            },
          ),
        );
      }
    );
  }

  Widget waitLayer() {
    ThemeData theme = Theme.of(context);

    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      color: Theme.of(context).primaryColor,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '乐驾',
              style: TextStyle(
                color: theme.cardColor,
                decoration: TextDecoration.none,
                letterSpacing: 20,
                fontSize: 70
              )
            ),
            Text(
              '学车',
              style: TextStyle(
                color: theme.cardColor,
                decoration: TextDecoration.none,
                letterSpacing: 20,
                fontSize: 70
              )
            )
          ], 
        )
      )
    );
  }

  // 控制浮层的显示
  Widget whichLayer() {
    Widget wl;
    switch (this.layer) {
      case 0:
        wl = SizedBox();
        break;
      case 1:
        wl = settingLayer();
        break; 
      case 3:
        wl = waitLayer();
        break;  
      default:
        wl = SizedBox();
        break;
    }
    return Stack(
      children: <Widget>[
        examsLayer(),
        wl
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Scaffold(
          appBar: AppBarWith3Part(
            back: true,
            content: appBarBtns(),
            action: setting(),
            height: fitSize(95),
            color: Theme.of(context).primaryColor,
          ),
          body: Container(
            color: Theme.of(context).primaryColor,
            height: 900.0,
            child: PageView.builder(
              itemBuilder: ((context, index) {
                return questionContent(subjectList[index], index);
              }),
              itemCount: subjectList.length,
              scrollDirection: Axis.horizontal,
              controller: _examsPageCtrl,
              onPageChanged: (index) {
                setState(() {
                  curPage = index;
                });
                Provider.of<SubLenModel>(context, listen: false).setCurSubIndex(index + 1);
              },
            ),
          )
        ),
        whichLayer()
      ],
    );
  }
}